package com.takeoutsystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.takeoutsystem.bean.AdminAccount;
import com.takeoutsystem.bean.Cabinet;
import com.takeoutsystem.bean.StorageRemainShow;
import com.takeoutsystem.event.publisher.SendMailPublisher;
import com.takeoutsystem.service.*;
import com.takeoutsystem.service.impl.CabinetServiceImpl;
import com.takeoutsystem.support.EnCryptAndDeCryptUtil;
import com.takeoutsystem.support.GenerateCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@Slf4j
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    AdminAccountService adminAccountService;
    @Autowired
    CabinetService cabinetService;
    @Autowired
    TakeoutHistoryService historyService;
    @Autowired
    SendMailPublisher mailPublisher;
    @Autowired
    RemainTakeoutShowService remainShowService;


    /**
     * 跳转登录页面
     * @return
     */
    @GetMapping("/login")
    public String getLoginPage(){
        return "login";
    }

    /**
     * 生成4位图片验证码
     * @param response
     * @param session
     */
    @GetMapping("/captcha")
    public void getCaptchaImg(HttpServletResponse response, HttpSession session){
        try{
            OutputStream os=response.getOutputStream();
            String capCode = GenerateCodeUtil.outputVerifyImage(100, 40,os,4);
            os.flush();
            os.close();
            session.setAttribute("capCode",capCode);
        }catch (Exception e){
            log.error("{}",e.getMessage());
        }
    }
    /**
     * 登录验证
     */
    @PostMapping("/doLogin")
    public String doLogin(AdminAccount account, @RequestParam("captcha") String captcha, Model model,
                          HttpSession session, HttpServletResponse response, HttpServletRequest request){
        //使用原生servlet获取请求值
        String autoLogin=request.getParameter("autoLogin");




        if(!session.getAttribute("capCode").equals(captcha)){
            //检查验证码是否正确
            model.addAttribute("failMsg","验证码错误!");
            return "login";
        }else if(!adminAccountService.checkLogin(account)){
            //检查账号密码匹配性
            model.addAttribute("failMsg","账号不存在或密码错误!");
            return "login";
        }else {
            //登录成功状态
            session.setAttribute("user",account);
            session.setAttribute("username",account.getUsername());
            //勾选了自动登录,添加cookie
            Cookie cookie = new Cookie("autoLogin",null);
            if(autoLogin!=null){
                String str=account.getUsername()+"_"+account.getPassword();
                try{
                    cookie.setValue(EnCryptAndDeCryptUtil.encryptBase64(str));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            cookie.setMaxAge(5*24*60*60);
            cookie.setPath(request.getContextPath()+"/");
            response.addCookie(cookie);
        }
        return "redirect:/admin/index";
    }


    /**
     * 跳转首页,查询所有外卖柜信息
     */
    @GetMapping("/index")
    public String getAllCabList(@RequestParam(value = "pid",defaultValue = "1")int pid,
                                @RequestParam(value = "maxNum",defaultValue = "5")int maxNum,Model model,HttpSession session){
        Page<Cabinet> page=cabinetService.selectAll(pid,maxNum);
        model.addAttribute("records",page.getRecords());
        model.addAttribute("pid",page.getCurrent());
        model.addAttribute("totalPage",page.getPages());
        model.addAttribute("pageSize",page.getSize());
        model.addAttribute("firstIndex",(page.getCurrent()-1)*page.getSize());
        model.addAttribute("url","index");
        List<Map<String,Integer>> countCabList=cabinetService.countByState();
        //统计各个状态存柜信息
        countCabList.forEach(
                (item)->{
                    String key="cabStateCount"+item.get("state");
                   session.setAttribute(key,item.get("count"));
                }
        );
        //统计存取记录总数
        session.setAttribute("historyCount",historyService.countAllRecords());

        return "admin/index";
    }
    /**
     * 按存柜状态分类筛选
     */
    @GetMapping("/filterByState")
    public String filterByState(@RequestParam(value = "code",defaultValue = "1")int code,
                                @RequestParam(value = "pid",defaultValue = "1")int pid,
                                @RequestParam(value = "maxNum",defaultValue = "5")int maxNum,Model model){
        Page<Cabinet> page=cabinetService.selectByStatus(code,pid,maxNum);
        model.addAttribute("records",page.getRecords());
        model.addAttribute("pid",page.getCurrent());
        model.addAttribute("totalPage",page.getPages());
        model.addAttribute("pageSize",page.getSize());
        model.addAttribute("firstIndex",(page.getCurrent()-1)*page.getSize());
        model.addAttribute("url","filterByState");
        model.addAttribute("code",code);
        return "admin/index";
    }
    /**
     * 按柜号查询存柜信息
     */
    @PostMapping("/selectById")
    public String selectById(@RequestParam("id")String id,Model model){
        model.addAttribute("records",cabinetService.selectByCabNumber(id));
        model.addAttribute("firstIndex",0);
        model.addAttribute("queryMode",true);
        model.addAttribute("searchId",id);
        return "admin/index";
    }

    /**
     * 按星期获取统计记录数
     */
    @GetMapping("/countByWeek")
    @ResponseBody
    public int[] countByWeek(){
        return historyService.countByWeek();
    }


    /**
     * 发送短信
     */
    @GetMapping("/sendMail")
    @ResponseBody
    public Map<String,Object> sendMail(@RequestParam(value = "mailMode",defaultValue = "1") Integer cmd,
                                       @RequestParam("cabId") String cabId){
        Map<String,Object> model=new HashMap<>();
        //获取存餐信息
        StorageRemainShow info=remainShowService.getById(cabId);
        if(info!=null){
            model.put("result",true);
            model.put("telNum",info.getUserTel());
            if(cmd==1){
                //发送取餐提醒短信
                mailPublisher.sendGetOrderMail(info);
                model.put("mode",1);
            }else{
                //发送超12h清除提醒短信
                mailPublisher.sendTimeOutMail(info);
                model.put("mode",2);
            }
        }else{
            model.put("result",false);
        }
        return model;
    }

    /**
     * 管理员修改密码
     */
    @PostMapping("changePassword")
    @ResponseBody
    public Boolean changePassword(@RequestParam("newPassword") String newPsw,@RequestParam("oldPassword") String oldPsw,
                                 HttpSession session){
        AdminAccount account=(AdminAccount) session.getAttribute("user");
        //旧密码输入错误，拒绝修改密码
        if(!oldPsw.equals(account.getPassword())){
            return false;
        }else{
            //修改新密码
            account.setPassword(newPsw);
            adminAccountService.changePassword(account);
            //清除session中有关账户的内容
            session.setAttribute("user",null);
            session.setAttribute("username",null);
            return true;
        }
    }
    /**
     * 管理员退出登录
     */
    @GetMapping("quitLogin")
    public String quitLogin(HttpServletRequest request, HttpServletResponse response,HttpSession session){
        //清除自动登录cookie
        Cookie cookie=new Cookie("autoLogin",null);
        cookie.setPath(request.getContextPath()+"/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        //清除session中有关账户的内容
        session.setAttribute("user",null);
        session.setAttribute("username",null);
        //重定向到登录页
        return "redirect:/admin/login";
    }

}
